<template>
  <!-- 地块信息 制作时间：2024-3-12 -->
  <div class="traceability">
    <!-- <div class="back" @click="back()">
        <i class="el-icon-back"></i>返回
    </div> -->
    <el-button icon="el-icon-arrow-left" @click="back()">返回</el-button>
    <!-- 列表 -->
    <div class="tableList">
      <div class="bindTitle">溯源码样式：</div>
      <div  class="tableFlex">
        <div>
          <div class="scanBox">
            <img src="@/assets/img/line.png" class="line"/>
            <img src="@/assets/img/horizontal.png" class="horizontal"/>
            <span class="lineText">5cm</span>
            <span class="horizontalText">5cm</span>
            <div id="exportContainer">
              <div class="scanTitle">食品安全看得见</div>
              <div class="scanImage">
                <img src="@/assets/img/leftStar.png" class="scanStar"/>
                <img :src="!(id && allData.link) ? require('@/assets/img/scan.png') : allData.link" class="scan"/>
                <img src="@/assets/img/rightStar.png" class="scanStar"/>
              </div>
              <div class="scanBottom">溯源编码：<span class="greenColor">{{ id ? allData.id : '编号自动生成'}}</span></div>
            </div>
          </div>
        </div>
        <div class="bindInput">
          <el-form
            :model="form"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm errorForm"
          >
            <el-form-item class="noRequire" label="*宣传语：" prop="slogan">
              <el-input class="widthEl" v-model="form.slogan" placeholder="请输入宣传语" />
            </el-form-item>
            <el-form-item class="noRequire" label="*作物图片：" prop="slogan"  v-if="$route.query.id">
                <upload
                  ref="upload"
                  v-model="form.icon"
                  :isShowTip="false"
                  :limit="1">
                </upload>
            </el-form-item>
            <el-form-item class="noRequire" label="绑定作物：" v-show="!$route.query.id">
              <el-button v-if="!detail.length && !$route.query.id" class="bindBtn" type="primary" @click="toNext()">
                绑定作物
              </el-button>
              <div class="bindBtnChange" v-else>
                <div class="bindLogo" v-for="(item, index) in detail" :key="item.id"  @mouseenter="showClose = true, logoId = index" @mouseleave="showClose = false, logoId = null">
                  <i class="el-icon-error" @click="detail.splice(index, 1)" v-if="showClose && logoId === index"/>
                  <div><span class="greyColor">种类名称：</span>{{item.seedInfo ?`${item.agriculturalTypeName} - ${item.seedInfo}`  : item.agriculturalTypeName }}</div>
                  <div><span class="greyColor">地块名称：</span>{{ item.landName }}</div>
                  <div><span class="greyColor">采收时间：</span>{{ item.time }}</div>
                </div>
              </div>
            </el-form-item>
            <el-form-item class="noRequire" label="*产品名称：" prop="seedInfo" v-if="$route.query.id">
              <el-input class="widthEl" v-model="form.seedInfo" placeholder="请输入产品名称" />
            </el-form-item>
            <el-form-item label="产品介绍：" prop="customText" v-if="$route.query.id">
              <el-input  class="widthInput" v-model="form.customText" show-word-limit maxlength="50" rows="4" type="textarea" placeholder="请简单介绍一下产品的特点～">
              </el-input>
            </el-form-item>
            <el-form-item class="noRequire" label="检测报告：" v-if="$route.query.id" >
              <el-button class="bindBtn" type="primary" @click="toNext()">
                修改检测报告
              </el-button>
              <div class="redColorFt">Tips：检测报告默认为全部添加</div>
            </el-form-item>
            <el-form-item class="noRequire" label="" v-if="!$route.query.id && detail.length" >
              <el-button class="bindBtn bindChange" type="primary" @click="toNext()">
                更改绑定作物
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
    <div class="addBtn">
        <el-button type="primary" v-if="$route.query.printing == 2" @click="downImg()">
          打印溯源码
        </el-button>
        <el-button type="primary" v-else @click="generate('ruleForm')">
          {{ id ? '修改' : '生成溯源码' }}
        </el-button>
    </div>
    <agriLand ref="agriLand" />
    <report ref="report" />

    <el-dialog
      :title="''"
      :visible.sync="dialogprnt"
      width="400px"
      :before-close="back"
      append-to-body
      class="dialog dialogPrint"
    >
      <div class="prntTitle">溯源码已生成</div>
      <div class="prntTitle">使用手机扫描进行查看</div>
      <div class="scanBox">
        <div id="exportContainer">
          <div class="scanTitle">食品安全看得见</div>
          <div class="scanImage">
            <img src="@/assets/img/leftStar.png" class="scanStar"/>
            <img :src="!linkTracing.link ? require('@/assets/img/scan.png') : linkTracing.link" class="scan"/>
            <img src="@/assets/img/rightStar.png" class="scanStar"/>
          </div>
          <div class="scanBottom">溯源编码：<span class="greenColor">{{ linkTracing.id ? linkTracing.id : '编号自动生成'}}</span></div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTracingSource, getTracingDetailApi, updateTracing, getTracingConditionApi } from '@/api/baseInfo'
import agriLand from './component/agriLand'
import report from './component/report'
import { getAgriListByTimeApi } from '@/api/mission'
import { getLandDetailApi } from '@/api/agriLand'
import html2canvas from 'html2canvas'
import upload from '@/views/agriMissionAdd/components/upload'
export default {
  name: 'traceabilityBind',
  components: {
    agriLand,
    upload,
    report
  },
  data () {
    return {
      dialogprnt: false,
      logoId: null,
      printObj: {
        id: 'printMe', // id
        popTitle: '标题' // 自定义设置标题
      },
      detail: [],
      form: {
        slogan: '',
        customText: '',
        seedInfo: '',
        icon: ''
      },
      id: 0,
      allData: {},
      baseId: 0,
      showClose: false,
      jsonData: [],
      params: {
        baseId: this.$store.getters.userInfo.baseId,
        landId: ''
      },
      rules: {
        slogan: [{ required: true, message: '请输入宣传语', trigger: 'blur' }],
        icon: [{ required: true, message: '请选择作物图片', trigger: 'change' }],
        seedInfo: [{ required: true, message: '请输入产品名称', trigger: 'blur' }]
      },
      linkTracing: {}
    }
  },
  created () {
    this.id = this.$route.query.id
    this.baseId = this.$store.getters.userInfo.baseId
    if (this.id) {
      this.getDetail()
    }
  },

  methods: {
    downImg () {
      const dom = document.getElementById('exportContainer')
      this.exportToImage(dom, '溯源码')
    },
    exportToImage (exportContent, title) {
      html2canvas(exportContent, {
        useCORS: true,
        height: exportContent.scrollHeight - 1, // canvas高, 高度减 1 是为了解决底部出现白线问题
        width: exportContent.scrollWidth // canvas宽
      }).then((canvas) => {
        const imageDataUrl = canvas.toDataURL('image/png')
        const downloadLink = document.createElement('a')
        downloadLink.href = imageDataUrl
        downloadLink.download = `${title}.png`
        downloadLink.click()
      })
    },
    // 地块名称
    landNameGet (list) {
      if (!this.id) {
        return
      }
      let landName = null
      list.map(item => {
        if (item.landId === this.allData.landId) {
          landName = item.landName
        }
      })
      this.detail.map((item, index) => {
        this.$set(item, 'landId', this.allData.landId)
        this.$set(item, 'landName', landName)
        this.jsonData[index].time = item.time
        this.$set(item, 'jsonData', this.jsonData[index])
      })
    },
    // 获取详情数据
    async getDetail () {
      await getTracingDetailApi({ id: this.id }).then(res => {
        this.$set(this, 'allData', res.data)
        // this.$set(this, 'detail', res.data && res.data.json.length ? res.data.json : [])
        // this.$set(this, 'jsonData', res.data && res.data.jsonData ? JSON.parse(res.data.jsonData) : [])
        this.form.slogan = res.data ? res.data.slogan : ''
        this.form.seedInfo = res.data ? res.data.seedInfo : ''
        this.form.customText = res.data ? res.data.customText : ''
        this.form.icon = res.data ? res.data.icon : ''
        // this.$refs.agriLand.getSysSonDictList()
      })
      this.params.landId = this.allData.landId
      this.params.baseId = this.allData.baseId
      const landData = await getLandDetailApi(this.params)
      await getAgriListByTimeApi(this.params).then(res => {
        res.data.find(item => {
          console.log(item.id == this.allData.havestingId)
          if (item.id == this.allData.havestingId) {
            item.landName = landData.data[0].landName
            this.$set(this, 'detail', [item])
            return true
          }
        })
      })
    },
    // 返回
    back () {
      this.$router.go(-1)
    },
    toNext () {
      if (this.$route.query.id) {
        this.$refs.report.openShow(this.allData)
      } else {
        this.$refs.agriLand.openShow(this.detail)
      }
    },
    showDetail (content) {
      // this.detail.unshift(content)
      this.$set(this, 'detail', [content])
    },
    // 报告id
    showIdList (content) {
      console.log(content)
      this.form = {
        ...this.form,
        ...content
      }
    },
    generate (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.$confirm(`是否${this.id ? '修改' : '生成'}溯源码?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (this.id) {
              updateTracing({
                ...this.allData,
                ...this.form
              }).then(() => {
                this.$message({
                  type: 'success',
                  message: '生成成功'
                })
                // this.getAgriList(this.params)
                this.$router.push({ path: '/centerindustry/traceability' })
              })
              return
            }
            getTracingSource({
              // ...this.detail,
              harvestid: this.detail.length ? this.detail[0].id : null,
              slogan: this.form.slogan
            }).then(res => {
              if (res.code === 200) {
                this.$message({
                  type: 'success',
                  message: '生成成功'
                })
                this.getTracDetail(res.data)
              } else {
                this.$message({
                  type: 'warning',
                  message: '生成失败'
                })
              }
              // this.getAgriList(this.params)
              // this.$router.push({ path: '/centerindustry/traceability' })
            })
          }).catch(Error => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
        }
      })
    },
    // 获取溯源详情
    getTracDetail (id) {
      getTracingDetailApi({
        id: id
      }).then(res => {
        this.dialogprnt = true
        this.linkTracing = res.data
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.redColor {
    color: #F76560
}
.greenColor {
    color: #00C586
}
.traceability {
    background: #fff;
}
.tableList {
  width: 85%;
  margin: 25px auto 0 auto;
  .tableFlex {
    display: flex;
    justify-content: space-between;
    > div {
      width: 40%
    }
    .bindInput {
      width: 60% !important
    }
  }
}
.addBtn {
  margin-top: 50px;
  text-align: center;
  .el-button {
    padding: 10px 35px;
    background: #00C586;
    border-color: #00C586;
  }
}
.bindInputScan {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  > span {
    font-size: 14px;
    width: 85px;
    text-align: right;
  }
}
.widthEl{
  width: 220px;
}
.bindTitle {
  font-weight: 500;
  font-size: 18px;
  margin-bottom: 30px
}
.scanBox {
    width: 310px;
    height: 310px;
    background: #fff;
    font-size: 22px;
    position: relative;
    border: 1px solid #00C586;
    > div {
      padding: 0 15px;
    }
    .scanTitle {
        text-align: center;
        padding: 30px 0 25px 0;
        background: #fff;
        font-weight: bold;
        color: #333
    }
    .scanImage {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .scan {
          width: 135px;
          height: 135px;
        }
        .scanStar {
          width: 50px;
        }
        ::v-deep #canvas {
          text-align: center;
          img {
            width: 150px;
            height: 150px;
            margin: auto
          }
        }
    }
    .line {
      position: absolute;
      width: 6px;
      left: -14px;
      top: 0;
      height: 100%;
    }
    .horizontal {
      position: absolute;
      left: 0;
      bottom: -16px;
      height: 6px;
      width: 100%;
    }
    .lineText {
      position: absolute;
      left: -42px;
      top: 0;
      bottom: 0;
      display: flex;
      align-items: center;
      margin: auto;
      color: #999999;
      font-size: 12px
    }
    .horizontalText {
      position: absolute;
      left: 0;
      right: 0;
      margin: auto;
      text-align: center;
      bottom: -30px;
      width: 100%;
      color: #999;
      font-size: 12px
    }
    .scanBottom {
        padding: 15px 0 0 0;
        text-align: center;
        font-size: 14px;
        font-weight: bold;
    }
}
.bindBtnChange {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-end;
  line-height: 100%;
}
.bindBtn {
  background: #00C586;
  border: 1px solid #00C586;
  color: #fff;
  padding: 9px 11px;
  font-size: 12px;
}
.bindChange {
  background: #fff;
  border: 1px solid #00C586;
  color: #00C586;
}
.bindLeftBtn {
  margin: 0.6rem 0 0 1.15rem;
  padding: 0.18rem 1.1rem;
}
.bindLogo {
  min-width: 200px;
  margin-right: 15px;
  padding: 10px;
  background: #FAFAFA;
  border-radius: 2px;
  position: relative;
  .el-icon-error {
    font-size: 14px;
    position: absolute;
    right: -7px;
    top: -5px;
    color: #F76560
  }
  > div + div {
    padding-top: 15px;
    display: flex;
    align-items: center;
  }
  img {
    width: 0.22rem;
    margin-right: 0.1rem
  }
}
.dialogPrint {
  ::v-deep .el-dialog {
    border-radius: 0.2rem !important;
    margin-top: 9vh !important;
    .scanBox {
      width: 250px;
      height: 250px;
      background: #fff;
      font-size: 22px;
      position: relative;
      border: 6px solid #00C586;
      margin: auto;
      > div {
        padding: 0 0.3rem;
      }
      .line {
        position: absolute;
        right: -0.32rem;
        top: 0;
        height: 100%;
      }
      .horizontal {
        position: absolute;
        left: 0;
        bottom: -0.35rem;
        width: 100%;
      }
      .lineText {
        position: absolute;
        right: -0.53rem;
        top: 0;
        bottom: 0;
        display: flex;
        align-items: center;
        margin: auto;
        color: #19B560;
        font-size: 0.15rem
      }
      .horizontalText {
        position: absolute;
        left: 0;
        right: 0;
        margin: auto;
        text-align: center;
        bottom: -0.48rem;
        width: 100%;
        color: #19B560;
        font-size: 0.15rem
      }
    }
    .scanTitle {
      text-align: center;
      padding: 20px 0 15px 0;
      background: #fff;
      font-weight: bold;
      color: #333;
    }
    .scanBottom {
      padding-top: 0
    }
    .el-dialog__title {
      padding: 0 0.5208vw;
      font-weight: 500;
    }
    .el-icon-close {
      font-size: 24px;
    }
    .el-dialog__body {
      padding: 0 20px 50px 20px;
    }
    .prntTitle {
      color: #333333;
      font-size: 18px;
      line-height: 28px;
      text-align: center;
    }
    .prntTitle+.prntTitle {
      margin-bottom: 20px;
    }
    .scanImage {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .scan {
        width: 135px;
        height: 135px;
      }
      .scanStar {
        width: 45px;
      }
      ::v-deep #canvas {
        text-align: center;
        img {
          width: 150px;
          height: 150px;
          margin: auto
        }
      }
    }
  }
}
</style>
